<%@ page import="java.sql.Connection" %>
<%@ page import="bean.UserBean" %>
<%@ page import="java.sql.*" %>
<%--
  Created by IntelliJ IDEA.
  User: 113
  Date: 2020/10/22
  Time: 16:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<jsp:useBean id="username" class="bean.UserBean" scope="application"></jsp:useBean>
<jsp:setProperty name="username" property="*"></jsp:setProperty>
<%
    //加载驱动
    Class.forName("com.mysql.jdbc.Driver");

    //建立连接
    String url ="jdbc:mysql://localhost:3306/book";
    Connection connection = DriverManager.getConnection(url,"root","root");
    //sql语句模板
    connection.setAutoCommit(false);
    String sql = "insert into user (username,password,gender,age,id) values (?,?,?,?,?)";//在PreparedStatement中使用问好代替实际参数
    PreparedStatement ps =connection.prepareStatement(sql);

    //参数赋值
    UserBean user = new UserBean();
    ps.setString(1,user.getUsername());
    ps.setString(2,user.getPassword());
    ps.setInt(3,user.getGender());
    ps.setInt(4,user.getAge());
    ps.setInt(5,0);

     ps.addBatch();
    int[] count = {0};
    try{
        count=ps.executeBatch();
        connection.commit();
    }
    catch(java.sql.SQLException e){
        connection.rollback();
        e.printStackTrace();
    }
    if(count[0] > 0){
        out.print("添加成功");
    }else{
        out.print("添加失败");
    }

    response.setHeader("refresh","3;url=home.jsp");

%>
